package com.nioSocketCore.chapter01;

import java.nio.CharBuffer;

/**
 *
 * 缓冲区 排入排出
 * */
public class BufferFillDrain {


    private static int index = 0;
    private static String[] strings = {
            "A random string value",
            "The product of an infinite number of monkeys",
            "Hey hey we're the Monkees",
            "Opening act for the Monkees: Jimi Hendrix",
            "'Scuse me while I kiss this fly", // Sorry Jimi ;-)
            "Help Me! Help Me!",
    };


    /**
     * 装入 data
     * */
    private static boolean fillBuffer(CharBuffer buffer) {
        /*超过  字符串数组长度, 直接返回 */
        if (index >= strings.length) {
            return (false);
        }
        String string = strings[index++];

        for (int i = 0; i < string.length(); i++) {
            buffer.put(string.charAt(i));
        }

        return (true);
    }

    /**
     * 排出data
     * */
    private static void drainBuffer(CharBuffer buffer) {
        System.out.print("INFO drainBuffer " );
        while (buffer.hasRemaining()) {
            System.out.print( (char) buffer.get());
        }
        System.out.println("");
    }

    public static void main(String[] argv) throws Exception {
        CharBuffer buffer = CharBuffer.allocate(100);
        for (int i = 0; i < buffer.capacity(); i++) {

            buffer.put("-");

        }
        System.out.println("  capacity () =" + buffer.capacity() + " limit() =" + buffer.limit() + "  position() = " + buffer.position());
        buffer.flip();  //position重置了
        System.out.println("  capacity () =" + buffer.capacity() + " limit() =" + buffer.limit() + "  position() = " + buffer.position());
        while (fillBuffer(buffer)) {  // 一直填数据,  直至 数据装完为止 ;

            System.out.println(" A capacity () =" + buffer.capacity() + " limit() =" + buffer.limit() + "  position() = " + buffer.position());
         //   buffer.flip();
            System.out.println(" B capacity () =" + buffer.capacity() + " limit() =" + buffer.limit() + "  position() = " + buffer.position());
            drainBuffer(buffer);
            buffer.clear();
            System.out.println(" C capacity () =" + buffer.capacity() + " limit() =" + buffer.limit() + "  position() = " + buffer.position());
        }
    }
}
